import React, { useState } from 'react';
import { Form, Input, Button, message, Spin } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import authService from '../../services/AuthService';
import { handleLoginError } from '../../utils/errorHandler';
import '../../styles/Login.css';

const Login = ({ onLogin }) => {
  const [loading, setLoading] = useState(false);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // 确保输入值存在
      if (!values.username || !values.password) {
        message.error('请输入用户名和密码');
        return;
      }

      const response = await authService.login(values.username, values.password);
      
      // 检查响应是否有效
      if (!response) {
        message.error('登录失败，请稍后重试');
        return;
      }
      
      if (response.success && response.token) {
        message.success('登录成功！');
        // 传递token和用户信息
        onLogin(response.token, response.user);
      } else {
        // 处理登录失败的情况
        const errorMessage = response.message || '用户名或密码错误，请重新输入';
        message.error(errorMessage);
      }
    } catch (error) {
      // 使用统一的错误处理函数
      console.error('登录过程中发生错误:', error);
      handleLoginError(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={loading}>
      <Form
        name="login"
        className="login-form"
        onFinish={onFinish}
        autoComplete="off"
        size="large"
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: '请输入用户名！',
            },
          ]}
        >
          <Input 
            prefix={<UserOutlined />} 
            placeholder="用户名" 
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
          />
        </Form.Item>

        <Form.Item>
          <Button 
            type="primary" 
            htmlType="submit" 
            className="login-form-button"
            block
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </Spin>
  );
};

export default Login;